<template>
  <div class="mailSet">
    <header class="set-header">
      <span class="auto_title">绑定邮箱列表</span>
      <el-button size="mini" type="primary" @click="bindNew">
        +绑定新邮箱
      </el-button>
    </header>
    <div class="gray"></div>
    <!-- 列表数据一-->
    <div class="list-show">
      <el-table :data="emailList" stripe class="table"  :height="$height - 230+'px'">
        <el-table-column label="邮箱账户" prop="emailAddr"></el-table-column>
        <el-table-column label="是否为默认邮箱">
          <template slot-scope="scope">
            <span style="color: #0a6cd6">{{scope.row.isDefault?'默认邮箱':'非默认邮箱'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="$refs.dialogEmail.init(scope.row)">查看</el-button>
            <el-button size="small" type="text" @click="delRow(scope.row)">解绑</el-button>
            <el-button size="small" type="text" @click="edit(scope.row,1)">编辑</el-button>
            <el-button size="small" type="text" @click="setDefault(scope.row.id)" v-if="!scope.row.isDefault">设为默认邮箱
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :visible.sync="dialogVisible" width="600px" :before-close="close"
               :close-on-click-modal="false" :close-on-press-escape='false'
               :title="form.id?'编辑邮箱信息':'绑定新邮箱'" center>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="130px" @keyup.enter.native="submit">
        <el-form-item label="邮箱账号:" prop="emailAddr">
          <el-input v-model="form.emailAddr" size="small" placeholder="请输入邮箱账号" :readonly="form.id!=''"></el-input>
        </el-form-item>
        <el-form-item label="邮箱密码/授权码:" prop="passWord" class="password">
          <span class="el-icon-question" @mouseover="showMessage=true" @mouseleave="showMessage=false"></span>
          <el-input v-model="form.passWord" :type="!state?'password':'text'" size="small"
                    placeholder="使用邮箱密码或授权码绑定"></el-input>
          <i :class="state?'el-icon-view':'icon-yanjing'"
             :style="{top:state?'28%':'5%'}"
             @click="state=!state"></i>
        </el-form-item>
        <el-form-item v-if="!form.id" class="extra" label="协议类型:" prop="protocolType" >
          <el-select v-model="form.protocolType" size="small">
            <el-option label="IMAP" value="0"></el-option>
            <el-option label="POP3" value="1"></el-option>
          </el-select>
          <h6 class="email-http">(不推荐使用POP3协议，POP3协议只能同步收件箱)</h6>
        </el-form-item>
        <el-form-item v-else class="extra" label="协议类型:" >
          <p>{{filter(form.protocolType)}}</p>
        </el-form-item>
        <div v-show="!form.isShow">
          <el-form-item class="extra" label="发邮件服务器:" prop="Server">
            <el-input v-model="form.Server" size="small" placeholder="请输入发送服务器（smtp）" style="width: 230px;"></el-input>&nbsp;:
            <el-input v-model="form.ServerPort" size="small" type="number" placeholder="端口号" style="width: 86px;"></el-input>
            <el-checkbox v-model="form.smtpSslElse">SSL</el-checkbox>
          </el-form-item>
          <el-form-item class="extra" label="接邮件服务器:" prop="Imap4Server">
            <el-input v-model="form.Imap4Server" size="small" :placeholder="`请输入接收服务器（${form.protocolType==0?'IMAP':'POP3'}）`"
                      style="width: 230px;"></el-input>&nbsp;:
            <el-input v-model="form.Imap4Port" size="small"  type="number"  placeholder="端口号" style="width: 86px;"></el-input>
            <el-checkbox v-model="form.imapSslElse">SSL</el-checkbox>
          </el-form-item>
        </div>
        <el-form-item :label="form.isShow?'手动配置':'收起手动配置'" class="hand" @click.native="form.isShow=!form.isShow">
          <div v-show="errorMsg!=''" class="error" @click.stop="form.isShow=form.isShow">
            <b @click="guide">请查看绑定指引&nbsp;&nbsp;&nbsp;</b>
            {{errorMsg}}
          </div>
        </el-form-item>
      </el-form>
      <!--显示内容模态框-->
      <div class="email-message" v-show="showMessage" @mouseover.stop="showMessage=true"
           @mouseleave="showMessage=false">
        <p>1.登录您的邮箱，检查是否开启IMAP/SMTP服务，如果没有开启则开启</p>
        <p>2.登录邮箱后，在客户端设置中（不同邮箱位置不同）获取授权码，如果没有授权码功能则使用密码登录（授权码获取根据官方引导即可）</p>
        <p>3.在绑定界面使用邮箱、授权码或密码进行绑定</p>
        <p>4、绑定企业邮箱，需要手动配置，企业邮箱由于邮箱后缀（域名）不固定所以需要用户前往官方平台查看smtp/imap的服务器地址</p>
        <p class="spectial">注：qq、网易等个人邮箱为固定域名，用户无需手动填写，但如果绑定失败，请手动配置，其他类型的邮箱和企业邮箱都需要手动配置。</p>
      </div>
      <!-- 底部按钮-->
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="close" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="submit" :loading="showLoading">{{showLoading?'绑定中':'确 定'}}</el-button>
      </div>
    </el-dialog>
    <!--查看弹窗-->
    <DialogEmail ref="dialogEmail"></DialogEmail>
    <!-- 绑定-->
    <DialogBind ref="dialogBind" :currentEmail="currentEmail" @getData="getData"></DialogBind>
    <DialogEmailHelp ref="dialogEmailHelp" @getData="getData"></DialogEmailHelp>
  </div>
</template>

<script>
    import {query, setDefault, update, add} from "@/api/mail/admin/mail-set";
    import DialogEmail from "@/components/mail/set/DialogEmail";
    import DialogEmailHelp from "@/components/mail/set/DialogEmailHelp";
    import DialogBind from "@/components/mail/set/DialogBind";
    import {validateEmail} from '@/util/util'
    import emailJson from '../../../public/cdn/json/email'
    export default {
        name: "MailSet",
        components: {DialogEmail, DialogBind, DialogEmailHelp},
        data() {
            var checkEmail = (rule, value, callback) => {
                if (!validateEmail(value)) {
                    return callback(new Error('请输入正确格式的邮箱'));
                } else {
                    callback();
                }
            };
            return {
                state: false,
                dialogVisible: false,
                emailList: [],
                form: {
                    id: '',
                    emailAddr: '',
                    passWord: '',
                    protocolType: '0',
                    Imap4Server: '',//接收服务器
                    Server: '',//发送服务器
                    ServerPort: '',
                    Imap4Port: '',
                    isShow: true,
                    smtpSsl: 0,
                    imapSsl: 0,
                    smtpSslElse: true,
                    imapSslElse: false
                },
                rules: {
                    emailAddr: [
                        {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    passWord: [
                        {required: true, message: 'IMAP协议使用邮箱密码授权码绑定', trigger: 'blur'},
                    ],
                },
                errorMsg: '',
                currentEmail: '',
                showMessage: false,
                dialogWidth: '1200',
                showLoading:false
            }
        },
        mounted() {
            this.getData(1);//发送
        },
        methods: {
            close(){
                this.dialogVisible = false;
                this.showLoading=false;
            },
            guide() {
                this.dialogVisible = false;
                let row;
                //判断邮箱类型 163 ,126,163企业，qq
                if (this.form.emailAddr.indexOf('@qq') != -1) {
                    row = emailJson[2]
                } else if (this.form.emailAddr.indexOf('@163') != -1) {
                    row = emailJson[1]
                } else if (this.form.emailAddr.indexOf('@126') != -1) {
                    row = emailJson[0]
                } else {
                    row = emailJson[3]
                }
                this.$refs.dialogEmailHelp.init(this.form, this.errorMsg, row);
            },
            //绑定邮箱
            submit() {
                this.showLoading=true;
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.form.smtpSsl = this.form.smtpSslElse ? 1 : 0;
                        this.form.imapSsl = this.form.imapSslElse ? 1 : 0;
                        let target = JSON.parse(JSON.stringify(this.form));
                        delete target.smtpSslElse;
                        delete target.imapSslElse;
                        if (this.form.id) { //编辑更新
                            update(target, 1).then(res => {
                                this.dealEnd(res, 1)
                            }).catch(err => {
                                this.errorMsg = err['msg'];
                                this.showLoading=false;
                            });
                        } else { //新增
                            add(target, 1).then(res => {
                                this.dealEnd(res, 1)
                            }).catch(err => {
                                this.errorMsg = err['msg'];
                                this.showLoading=false;
                            });
                        }
                    } else {
                        this.showLoading=false;
                        return false;
                    }
                });
            },
            bindNew() {
                if (this.$refs.ruleForm) {
                    this.$refs.ruleForm.resetFields();
                }
                this.resetForm();
                this.dialogVisible = true;
            },
            //设为默认邮箱
            setDefault(id) {
                this.$confirm("确定所选邮箱设为默认邮箱吗?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success"
                }).then(() => {
                    setDefault(id).then(res => {
                        this.dealEnd(res, 1)
                    }).catch(err => {
                        console.log(err)
                    });
                }).catch(() => {
                })
            },
            //编辑
            edit(row) {
                if (this.$refs.ruleForm) {
                    this.$refs.ruleForm.resetFields();
                }
                this.resetForm();
                this.form.id = row.id;
                this.form.emailAddr = row.emailAddr;
                this.form.passWord = row.passWord;
                this.form.protocolType = row.protocolType.toString();
                this.form.Imap4Server = row.Imap4Server;
                this.form.Server = row.Server;
                this.form.ServerPort = row.ServerPort;
                this.form.Imap4Port = row.Imap4Port;
                this.form.smtpSsl = row.smtpSsl;
                this.form.imapSsl = row.imapSsl;
                this.form.smtpSsl = row.smtpSsl == 1;
                this.form.imapSsl = row.imapSsl == 1;
                this.form.isShow = row.Imap4Server != '';
                this.form.smtpSslElse = row.smtpSsl == 1;
                this.form.imapSslElse = row.imapSsl == 1;
                this.dialogVisible = true;
            },
            //解绑
            delRow(row) {
                this.$refs.dialogBind.init(row)
            },
            dealEnd(res, type) {
                this.showLoading=false;
                if (res.data.success) {
                    this.dialogVisible = false;
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                    this.form.id = '';
                    if (this.$refs.ruleForm) {
                        this.$refs.ruleForm.resetFields();
                    }
                    this.errorMsg = ''
                    this.$store.dispatch('update_emailList')
                    this.getData(type);
                } else {
                    this.errorMsg = res.data.msg
                }
            },
            getData(type) {
                query(type).then(res => {
                    if (res.data.success) {
                        this.emailList = res.data.data;
                        this.$store.commit('SET_EMAILLIST', this.emailList)
                    }
                }).catch(err => {
                    console.log(err)
                });
            },
            //重置
            resetForm() {
                this.form = {
                    id: '',
                    emailAddr: '',
                    passWord: '',
                    protocolType: '0',
                    Imap4Server: '',//接收服务器
                    Server: '',//发送服务器
                    ServerPort: '',
                    Imap4Port: '',
                    smtpSsl: 0,
                    imapSsl: 0,
                    smtpSslElse: true,
                    imapSslElse: false,
                    isShow: true,
                }
                this.state = false;
                this.errorMsg = ''
            },
            filter(type){
                switch (parseInt(type)) {
                    case 0:
                        return 'IMAP';
                    case 1:
                        return 'POP3';
                    case 2:
                        return 'Exchange';
                    default:
                        return 'IMAP'
                }
            }
        }
    }
</script>

<style lang="scss">
  $normalSize: 14px;
  $activeColor: #2A97F9;
  $bgColor: #E9F3FD;
  .mailSet {

    .email-message {
      position: absolute;
      right: -351px;
      top: -133px;
      border: 1px solid #80808061;
      background-color: #fff;
      z-index: 3;
      width: 370px;
      padding: 10px;
      border-radius: 5px;
      font-size: 12px;

      p {
        line-height: 25px;
      }

      p.spectial {
        color: red;
      }
    }

    form.el-form {
      width: 520px;
      margin: 0 auto;

      .el-form-item {
        margin-bottom: 12px !important;

        .el-checkbox {
          margin-left: 10px;
        }

      }

      p {
        font-size: 13px;

        span {
          color: #8C8C8C;
          font-size: 12px;
        }
      }
    }

    label.el-form-item__label {
      text-align: left
    }

    .el-form-item.extra {
      label.el-form-item__label {
        padding-left: 10px;
      }
    }
    .email-http{
      font-size: 12px;
      line-height: 20px;
    }
    span.el-icon-question {
      position: absolute;
      right: -22px;
      top: 10px;
      font-size: 18px;
      color: #6666666b;
    }

    .el-form-item.hand {

      label.el-form-item__label {
        color: #2A97F9;
        padding-left: 10px;
        cursor: pointer;
      }

      .error {
        margin-top: 5px;
        line-height: 25px;
        color: #F48A94;

        b {
          color: $activeColor;
          cursor: pointer;
        }
      }

    }

    .el-table td {
      font-size: 13px;
      padding: 4px 0;
    }

    .title {
      color: $activeColor;
      font-size: $normalSize;
      line-height: 35px;
      padding-left: 30px;
      background: #eaf0f6;

      span {
        color: #325893;
        margin-left: 15px;
        cursor: pointer;
      }
    }

    .list-show {
      margin: 20px 0 0 27px;
    }
  }
</style>
